#include "stdafx.h"
#include "Application.h"
#include "LogModule.h"
#include "NetworkModule.h"
#include "ProtoMgr.h"
#include "TimerMgr.h"
#include "session_manager.h"
#include "player_manager.h"
#include "SecondTimer.h"
#include "map_manager.h"

static volatile int g_bTerminated = false;

#ifdef WIN32
#include <Windows.h>
BOOL WINAPI console_handler(DWORD cevent)
{
    switch(cevent)
    {
    case CTRL_C_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_CLOSE_EVENT:
    case CTRL_LOGOFF_EVENT:
    case CTRL_SHUTDOWN_EVENT:
        {
            //your code here
            g_bTerminated = true;
            break;
        }
    default:
        {
        }
    }
    return TRUE;
}
#else
#include <signal.h>
#define Sleep usleep
void term_handler(int sig)
{
    g_bTerminated = true;
}
#endif

CApplication::CApplication(void)
{
    CLogModule::Instance();
    CNetworkModule::Instance();
    CProtoMgr::Instance();
    CPlayerSessionMgr::Instance();
    CSecondTimer::Instance();
    CMinuteTimer::Instance();
    CTimerMgr::Instance();
    CPlayerMgr::Instance();
    CMapMgr::Instance();
}


CApplication::~CApplication(void)
{
    CMapMgr::DestroyInstance();
    CPlayerMgr::DestroyInstance();
    CTimerMgr::DestroyInstance();
    CSecondTimer::DestroyInstance();
    CPlayerSessionMgr::DestroyInstance();
    CProtoMgr::DestroyInstance();
    CNetworkModule::DestroyInstance();
    CLogModule::DestroyInstance();
}

bool CApplication::Init()
{
    if (!CLogModule::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initializing log module";
        return false;
    }

    if (!CNetworkModule::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initialization of net module";
        return false;
    }

    if (!CTimerMgr::Instance()->Init())
    {
        LOG(CRITICAL) << "Failed on initialization of timer manager";
        return false;
    }

    LOG(INFO) << "Initialize successfully";

    return true;
}

void CApplication::Run()
{
    while(!g_bTerminated)
    {
        bool bBusy = false;

        bBusy |= CNetworkModule::Instance()->Run();
        bBusy |= CTimerMgr::Instance()->Run();
        if (!bBusy)
            Sleep(1);
    }
}

void CApplication::Terminate()
{
    g_bTerminated = true;
}
